package middleware

import (
	"dingusxp/trial/guestbook/server/log"
	"mime"
	"net/http"
	"time"
)

func Logging(next http.Handler) http.Handler {

	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		log.Info("REQUEST: ["+r.Method+"] "+r.URL.Path, "IP: "+r.RemoteAddr)
		now := time.Now()
		next.ServeHTTP(rw, r)
		log.Info("RESPONSE", "cost: "+time.Since(now).String())
	})
}

func Validating(next http.Handler) http.Handler {

	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		// only check post method
		if r.Method != "POST" {
			next.ServeHTTP(rw, r)
			return
		}

		contentType := r.Header.Get("Content-Type")
		mediaType, _, err := mime.ParseMediaType(contentType)
		if err != nil {
			logMsg := "parse media type failed: " + err.Error()
			http.Error(rw, logMsg, http.StatusUnsupportedMediaType)
			log.Warning(logMsg, "")
			return
		}
		if mediaType != "application/json" {
			logMsg := "invalid content-type " + mediaType
			http.Error(rw, logMsg, http.StatusUnsupportedMediaType)
			log.Warning(logMsg, "")
			return
		}
		next.ServeHTTP(rw, r)
	})
}
